﻿using System;
using System.Net;
using System.Threading.Tasks;
using DotNetStar.TheKing.Domain;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

namespace DotNetStar.TheKing.Web
{
    public class Program
    {
        public static void Main(string[] args)
        {

            var host = BuildWebHost(args);

            using (var scope=host.Services.CreateScope())
            {
                var service = scope.ServiceProvider;
                service.GetService<Infrastructure.NotificationSchedular>().Start();
                //try
                //{
                //    var context = service.GetService<TheKingDbContext>();
                //    DatabaseInitializer.Initialize(context);

                //}catch(Exception ex)
                //{
                //    var logger = service.GetService<ILogger<Program>>();
                //    logger.LogError(ex, "数据初始化有错误");
                //}
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
            .UseIISIntegration()
            .ConfigureAppConfiguration((hostingEnviroment,config) =>
            {
                var env = hostingEnviroment.HostingEnvironment;
                config.AddJsonFile("appsettings.json", false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, reloadOnChange: true);
                config.AddEnvironmentVariables();


                //new LoggerConfiguration().Enrich.FromLogContext().WriteTo
                //    .RollingFile(""+ env.ContentRootPath + "/logs/{Date}.log", Serilog.Events.LogEventLevel.Debug)
                //    .CreateLogger();
            })
            //.ConfigureLogging((hostingContext, logging) =>
            //{
            //    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            //    logging.AddConsole();
            //    logging.AddDebug();
            //})
            .UseKestrel(m =>
            {
                m.Listen(IPAddress.Loopback, 7000);
            })
                .Build();
    }
    
}
